package com.frejoys.task;

import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.CacheUtil;
import com.frejoys.dao.entity.Order;
import com.frejoys.service.OrderService;
import com.frejoys.service.RebateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

// 清理超时订单任务
@Slf4j
@Component
@RequiredArgsConstructor
public class ClearOrderTimeTask {

    // @Scheduled(cron = "{秒数} {分钟} {小时} {日期} {月份} {星期}")

    private final RedissonClient redissonClient;

    private final OrderService orderService;

    private final RebateService rebateService;

    /**
     * 每9分钟，将未支付超时的订单放入处理集合
     */
    @Async
    @Scheduled(cron = "0 */9 * * * ?")
    // @Scheduled(cron = "0 */1 * * * ?")
    public void timeoutOrderAddCache() {
        List<Order> orders = orderService.getNoPayTimeoutOrder(1, 1000);
        for (Order order : orders) {
            CacheUtil.addOrderTimeoutSortSet(order.getOrderSn(), order.getPayTime());
        }
    }

    /**
     * 每1分钟，处理超时未支付的订单
     * 将商品还原，订单失效
     */
    @Async
    @Scheduled(cron = "*/60 * * * * ?")
    public void clearOrder() {

        RLock lock = redissonClient.getLock(CacheKeyUtil.taskOrderTimeoutLockCacheKey());

        try {
            if (lock.tryLock(0, 60, TimeUnit.SECONDS)) {

                rebateService.timeoutOrder();

            }

        } catch (InterruptedException e) {
            // e.printStackTrace();
            log.error("清理超时订单异常：", e);
            Thread.currentThread().interrupt();
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

    }

}
